import React, { useEffect, useState } from "react";
import { ListType } from "../../Type/index";
import { useParams, useNavigate } from "react-router";
import http from "../../utils/http";
import { NavBar, Toast, Cell, ActionBar } from "react-vant";
import { CartO, ChatO, ShopO } from "@react-vant/icons";
import { useAppSelector, useAppDispatch } from "../../store/store";
import { addCart } from "../../store/CartSlice";

const Index: React.FC = () => {
  const navigate = useNavigate();

  const dispatch = useAppDispatch();
  const { CartList } = useAppSelector((state) => state.cart);
  const { id } = useParams();
  const [item, setItem] = useState<ListType>({} as ListType);

  // 获取数据
  const getData = async () => {
    const res = await http.get("/api/list/" + id);
    const { code, data, message } = res.data;
    if (code === 200) {
      setItem(data);
    } else {
      Toast.fail(message);
    }
  };
  useEffect(() => {
    getData();
  }, []);
  if (!item.body) {
    return <div>数据加载中...</div>;
  }

  // 添加购物车
  const handelAdd = () => {
    dispatch(addCart(item));
  };
  return (
    <div>
      <NavBar
        title="详情页"
        leftText="返回"
        onClickLeft={() => navigate("/")}
      />
      <img src={item.body.image} alt="" style={{ width: "100%" }} />
      <Cell
        title={item.body.name}
        value={item.body.price}
        label={item.body.desc}
      />
      <ActionBar>
        <ActionBar.Icon icon={<ChatO />} badge={{ dot: true }} text="客服" />
        <ActionBar.Icon
          icon={<CartO />}
          badge={{ content: CartList.length }}
          text="购物车"
          onClick={() => navigate("/cart")}
        />
        <ActionBar.Icon icon={<ShopO />} badge={{ content: 12 }} text="店铺" />
        <ActionBar.Button
          type="warning"
          text="加入购物车"
          onClick={() => handelAdd()}
        />
        <ActionBar.Button type="danger" text="立即购买" />
      </ActionBar>
    </div>
  );
};

export default Index;
